﻿#include "clientreadsession.h"
#include "utils.h"

#include <QFile>
#include <winsock.h>

namespace TFTP {


ClientReadSession::ClientReadSession(TransferInfo T, const QString &local, const QString &remote, TransferMode trmode)
    : TFTP::ReadSession(T)
{
    currentMode = trmode;
    currentBlock = 0;
    m_currentFile = new QFile(local);
    m_currentFile->open(QFile::WriteOnly | QFile::Append);

    sendRequest(remote);
}

ClientReadSession::ClientReadSession(TransferInfo T, QIODevice *data, const QString &remote, TransferMode trmode)
    : TFTP::ReadSession(T)
{
    currentMode = trmode;
    currentBlock = 0;
    m_currentFile = data;
    sendRequest(remote);
}


void ClientReadSession::sendRequest(const QString &remote)
{
    loadFile();

    QString modestring;
    switch( currentMode )
    {
    case Octet:
        modestring = "octet";
        break;
    case NetAscii:
        modestring = "netascii";
        break;
    default:
        qFatal("错误！传输操作中的模式无效！");
    }

    int  len = 2 + remote.length() + 1 + modestring.length() + 1;

    QByteArray dgram;
    dgram.resize(len);
    wordOfArray(dgram)[0] = htons( (quint16 )WRQ );

    memcpy( dgram.data()+2, remote.data(), remote.size() +1 );
    memcpy( dgram.data()+2+remote.length()+1, modestring.data(), modestring.length() +1 );

    qint64 len2 =  ti.sd->writeDatagram(dgram.data(), dgram.size(), ti.dAddr, ti.dPort);
    if(len2 == -1 ){
        qWarning("发送WRQ数据包时出错 [%d]", ti.sd->error() );
    }
}

ClientReadSession::~ClientReadSession()
{
}


};
